<template>
  <a-spin :spinning="confirmLoading">
    <!-- 主表单区域 -->
    <div>
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="采购入库单号" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="orderNo">
              <a-input v-model="model.orderNo" placeholder="请输入" :readOnly="disabled" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="仓库" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="warehouseId">
              <j-tree-select v-model="model.warehouseId" dict="bas_warehouse,aux_name,id" pidValue="0"
                hasChildField="has_child" placeholder="请选择" :disabled="disabled" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业务员" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="operator"
              ref="operatorFmi">
              <j-select-user-by-dep :disabled="disabled" v-model="model.operator" :multi="false"
                @change="onOperatorChange" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
           <a-col :span="8">
          <a-form-item label="备注" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="remark">
            <a-input placeholder="请输入" v-model="model.remark" :disabled="disabled" />
          </a-form-item>
        </a-col>
          <a-col :span="8">
            <a-form-model-item label="附件" :labelCol="labelCol3" :wrapperCol="wrapperCol3" prop="attachmentUrl">
              <j-upload v-model="model.attachmentUrl" :disabled="disabled"    ></j-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 子表单区域 -->
        <a-tabs v-model="activeKey" @change="handleChangeTabs">
          <a-tab-pane tab="明细" :key="refKeys[0]" :forceRender="true">
            <j-vxe-table keep-source :ref="refKeys[0]" :loading="entryTable.loading" :columns="entryTable.columns"
              :dataSource="entryTable.dataSource" :maxHeight="300" :disabled="disabled" :rowNumber="false"
              :rowSelection="!disabled" :toolbar="!disabled" :resizable="true"
              :edit-config="{ trigger: 'click', mode: 'row', showIcon: false }"
              @edit-actived="({ row }) => setMaterialUnitOptions(row, $refs.entryTable)" @added="onInEntryAdded"
              @valueChange="onEntryValueChange" />
          </a-tab-pane>

         
        </a-tabs>

      </a-form-model>
    </div>

  </a-spin>
</template>

<script>

import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { OrderFormMixin, OrderFormGridMixin } from '../../common/mixins/OrderFormMixin'
import { OrderVxeTableMixin } from '../../common/mixins/OrderVxeTableMixin'
import BillHeader from "../../common/components/BillHeader";
import BillFooter from "../../common/components/BillFooter";
import VxeTableColumnsSetter from "../../common/components/VxeTableColumnsSetter";

export default {
  name: 'CheckInForm',
  mixins: [JVxeTableModelMixin, OrderFormMixin, OrderFormGridMixin, OrderVxeTableMixin],
  components: { BillHeader, BillFooter, VxeTableColumnsSetter },

  data() {
    return {
      model: {//设置初始值的属性、程序赋值的响应式属性
        billNo: '',
        billDate: new Date().format('yyyy-MM-dd'),
        isAuto: 0,
        isRubric: 0,
        srcBillType: '',
        srcBillId: '',
        srcNo: '',
        stockIoType: '102', //盘盈入库
        hasRp: 0,
        hasSwell: 0,
      },

      validatorRules: {},

      entryNoStep: 10,
      addDefaultRowNum: 1,
      refKeys: ['entryTable',],
      tableKeys: ['entryTable',],
      activeKey: 'entryTable',
      // 明细
      entryTable: {
        loading: false,
        dataSource: [],
        url: { list: '/wr/materialRawInOrder/queryById' },
        columns: [
          {
            title: '#',
            key: 'entryNo',
            type: JVXETypes.inputNumber,
            width: "70px",
            align: "center",
            fixed: 'left',
            sortable: true,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [
              { required: true, message: '${title}不能为空' },
              { pattern: /^[1-9]\d*$/, message: '${title}须为正整数' },
              { unique: true, message: '${title}不能重复' },
            ],
          },
          
          {
            title: '物料',
            key: 'materialId',
            type: JVXETypes.selectSearch,
            dictCode: "bas_material,name,id",
            options: [],
            width: "300px",
            fixed: 'left',
             align: "center",
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
          
          {
            title: '入库数量',
            key: 'qty',
            type: JVXETypes.inputNumber,
            width: "200px",
            align: "center",
            formatter: this.formatQty,
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }, { handler: this.rubricValidator }],
         
          },
           {
            title: '单位',
            key: 'unitId',
             align: "center",
            type: JVXETypes.selectSearch,
            dictCode: "bas_unit,name,id",
            options: [],
            width: "110px",
            align: "center",
            placeholder: '请输入',
            defaultValue: '',
            validateRules: [{ required: true, message: '${title}不能为空' }],
          },
         
          {
            title: '备注',
            key: 'remark',
             align: "center",
            type: JVXETypes.input,
            defaultValue: '',
          },
          
        ]
      },
      url: {
        add: "/wr/materialRawInOrder/create",
        edit: "/stock/stkIo/edit",
        check: "/stock/stkIo/check",
        ebpm: "/stock/stkIo/bpm/end",
        execute: "/stock/stkIo/execute",
        void: "/stock/stkIo/void",
      },
    }
  },

  created() {
    if (!this.disabled) this.initMaterialRelated();
  },

  methods: {
    addBefore() {
      this.entryTable.dataSource = [];
    },

    addAfter() {
      this.$refs.billHeader.fillBillNo(
        'stk_pyrk_bill_no',
        (billNo) => {
          this.$nextTick(() => {
            //异步执行原因，初始空白行增加时，billNo可能还未获得！
            let rows = this.$refs.entryTable.getNewDataWithId();
            for (let row of rows) {
              this.$refs.entryTable.setValues([{ rowKey: row.id, values: { batchNo: billNo + '-' + row.entryNo } }]);
            }
          })
        });
    },

    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    editAfter() {
      setTimeout(() => {
        if (this.model.id) {
          let params = { id: this.model.id };
          this.requestSubTableData(this.entryTable.url.list, params, this.entryTable, () => {
            console.log('明细数据加载结果：', this.entryTable.dataSource); // 新增日志
            // 检查明细数据是否为空
            if (!this.entryTable.dataSource || this.entryTable.dataSource.length === 0) {
              console.warn('明细数据为空，可能接口返回空或参数错误');
            }
          });
        }
      }, 500);
    },

    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        details: allValues.tablesValue[0].tableData,
      }
    },

    onEntryValueChange(event) {
      const { type, value, oldValue, row, column, target, isSetValues } = event;
      if (value === oldValue || isSetValues) return;

      //如果使用col，注意其无property属性
      switch (column.property) {
        case "entryNo": //联动：分录号 --> 批次
          if (!row.batchNo || row.batchNo === this.model.billNo + "-" + oldValue) {
            target.setValues([{ rowKey: row.id, values: { batchNo: this.model.billNo + "-" + value } }]);
          }
          break;
        case "materialId":
          this.handleMaterialChange(row, target);
          break;
        case "unitId":
          if (!oldValue || oldValue.length === 0 || !value || value.length === 0) break;
          const rate = this.getUnitRate(row.materialId, oldValue, value);
          if (!rate)
            target.setValues([{ rowKey: row.id, values: { unitId: oldValue } }]);
          else
            target.setValues([{ rowKey: row.id, values: { qty: (row.qty * rate).toFixed(3) } }]);
          break;
      }
    },

  }
}
</script>

<style lang="less" scoped>
@import "../../common/less/BillForm.less";
</style>
